package com.quanyan.ic.vendingMachine.protocol.server.handler;

import com.quanyan.ic.vendingMachine.http.service.VmOrderService;
import com.quanyan.ic.vendingMachine.model.OrderItem;
import com.quanyan.ic.vendingMachine.protocol.Cmd;
import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageProto;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuo.shi on 2017/8/4.
 * 接收客户端出货成功响应消息，进行更新order_item和扣库存处理
 */
@Component("ShipGoodsRespHandler")
@ChannelHandler.Sharable
public class ShipGoodsRespHandler extends ChannelInboundHandlerAdapter {

    public static final Logger logger = LoggerFactory.getLogger(ShipGoodsRespHandler.class);

    @Autowired
    private VmOrderService vmOrderService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        VmMessageProto.VmMessage vmMessage = (VmMessageProto.VmMessage) msg;
        if (vmMessage.getCmd() != Cmd.SHIPGOODS_SUCCESS.getValue()) {
            ctx.fireChannelRead(msg);
            return;
        }
        logger.info("received cmd {}, msg=\n{}", Cmd.SHIPGOODS_SUCCESS.getDesc(), vmMessage);
        List<OrderItem> orderItems = new ArrayList<>();
        List<VmMessageProto.VmMessage.OrderSuccess> osList = vmMessage.getOsListList();
        for (VmMessageProto.VmMessage.OrderSuccess os : osList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(os.getOrderNo());
            orderItem.setGrid(os.getGrid());
            orderItem.setGridNumber((byte) os.getGridNumber());
            orderItem.setQty((byte) os.getQty());
            orderItem.setShipQty((byte) os.getShipQty());
            orderItems.add(orderItem);
        }
        if (orderItems.size() == 0) {
            logger.warn("ship goods: vmMessge not contains goods items");
            return;
        }
        vmOrderService.processOrderShipGoods(vmMessage.getVmNumber(), orderItems);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }
}
